import passport from 'koa-passport'

import { User } from '../../models'
/**
 * 获取待展示的用户数据
 * 
 * @export
 * @param {any} ctx 
 */
export async function getUsers(ctx) {

    var params = Object.assign(ctx.query, ctx.request.body.params);
    Object.assign(params, { limit: 10 });
    if (!params.page) {
        params.page = 1
    } else {
        params.page -= 1
    }
    
    var where = {status:1};
    if (params.name) {
        Object.assign(where, { name: params.name });
    }
    if (params.phone) {
        Object.assign(where, { phone: params.phone });
    }
    if (params.address) {
        Object.assign(where, { address: params.address });
    }
    if (params.age) {
        Object.assign(where, { age: params.age });
    }
    var count = await User.count({ where: where });
    var list = await User.getUsers(params);
    list.forEach(user => {
        var date = new Date(user.createdAt);
        user.joinTime = date.getTime() / 1000;
    });
    ctx.body = {
        lit: list,
        count: count
    }

}
/**
 * 修改用户信息
 * 
 * @export
 * @param {any} ctx 
 */
export async function updateUser(ctx) {
    const user = ctx.body.user;
    Object.assign(user, ctx.request.body)
    await user.save();
    ctx.body = { user }
}
/**
 * 删除用户信息
 * 
 * @export
 * @param {any} ctx 
 */
export async function deleteUser(ctx) {
    const user = ctx.body.user;
    user.status = 2;
    await user.save();
    ctx.status = 200;
    ctx.body = { success: true }
}
export async function getAllUsers(ctx) {
    const users = await User.findAllUsers();
    ctx.body = { data: users }
}
/**
 * 根据uid获取用户
 * 
 * @export
 * @param {any} ctx 
 * @param {any} next 
 * @returns 
 */
export async function getUser(ctx, next) {
        const uid  = ctx.request.body.uid
    try {
        const user = await User.findOne({ where: { uid: uid } });
        if (!user) {
            ctx.throw(404)
        }
        ctx.body = { user }
    } catch (err) {
        if (err === 404 || err.name === 'CastError') {
            ctx.throw(404)
        }

        ctx.throw(500)
    }

    if (next) {
        return next()
    }
}